import { Fragment } from "react";
import { useDidShow, useRouter } from "@tarojs/taro";
import { PageContainer, View } from "@tarojs/components";

import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";
import ByTag from "@/components/ui/ByTag";
import Money from "@/components/app/Money";
import Card from "@/components/common/Card";
import ByText from "@/components/ui/ByText";
import ByCell from "@/components/ui/ByCell";
import Page from "@/components/common/Page";
import ByButton from "@/components/ui/ByButton";
import ByCellGroup from "@/components/ui/ByCellGroup";
import CustomerCard from "@/components/app/CustomerCard";
import ApprovalaProcess from "@/components/app/ApprovalaProcess";

import ApiCrm from "@/api/crm";
import ApiWorkflow from "@/api/workflow";
import { objectToQueryString } from "@/utils";
import { enumReportTypeOptions } from "@/packageProject/utils/enum";

import useEnum from "@/hooks/useEnum";
import useFetch from "@/hooks/useFetch";
import useApproval from "@/hooks/useApproval";

import { IntentCustomerData } from "@/types/customer";
import { TaskDetail } from "@/types/global";

const cellProps = {
  size: "small",
  labelWidth: "5em",
} as const;

/**
 * 定额/材料详情
 */
const DetailItem = ({ source }: { source: any }) => {
  const { detailType, materialSalePrice, quotaPrice, materialNum, quotaNum } =
    source;

  const isMa = detailType === 1;

  const prefix = isMa ? "material" : "quota";
  return (
    <View>
      <View>
        <ByTag>{detailType === 1 ? "材料" : "定额"}</ByTag>
        <ByText bold className="pl-2">
          {source[`${prefix}Name`]}
        </ByText>
      </View>

      <ByRow className="mt-3" content="between">
        <ByCol span={6}>
          <ByText>
            <>{source[prefix + "Spec"]}</>
            <>{source[prefix + "Unit"]}</>
          </ByText>
        </ByCol>

        <ByCol span={3}>
          <ByText size="sm">
            <ByText type="third">数量：</ByText>
            <ByText>{isMa ? materialNum : quotaNum}</ByText>
          </ByText>
        </ByCol>

        <ByCol span={3} className="text-right">
          <Money value={isMa ? materialSalePrice : quotaPrice} />
          <ByText type="second" size="sm">
            /{source[prefix + "Unit"]}
          </ByText>
        </ByCol>
      </ByRow>
    </View>
  );
};

export default () => {
  const { params } = useRouter<{
    wl_id: `${number}`;
    businessId: string;
    intentCustomerId: `${number}`;
    workFlowDefinitionId: `${number}`;
  }>();

  const workflowInstanceId = Number(params.wl_id);
  const intentCustomerId = Number(params.intentCustomerId);
  const masterId = decodeURIComponent(params.businessId as string);

  // 获取签报详情
  const { data, run } = useFetch<any>(ApiWorkflow.signReportDetail, {
    manual: true,
    showLoading: true,
  });

  // 获取审批流节点
  const { data: workflowDetail, refresh: refreshWorkflowDetail } =
    useFetch<TaskDetail>(ApiWorkflow.detail, {
      defaultParams: [{ workflowInstanceId }],
      onSuccess(res: any) {
        run({ masterId, workFlowDefinitionId: res.workflowDefinitionId });
      },
    });

  // 客户详情
  const { data: customerDetail } = useFetch<IntentCustomerData>(
    ApiCrm.customerDetail,
    { defaultParams: [{ intentCustomerId }] }
  );

  // 提交审批结果
  const {
    approverNode,
    visible,
    PopupApproval,
    setApproveNode,
    onApproved,
    onRejected,
    onCancal,
  } = useApproval(refreshWorkflowDetail);


  useDidShow(() => {
    if (workflowDetail) refreshWorkflowDetail()
  })

  const { getOption } = useEnum(enumReportTypeOptions);
  return (
    <>
      <Page
        footerSticky
        slotFooter={
          !!approverNode && (
            <ByRow className="justify-around">
              {approverNode.isCanEdit && (
                <ByButton
                  className="flex-2 mr-2"
                  variant="filled"
                  type="warning"
                  size="large"
                  to={`apply?${objectToQueryString({
                    masterId,
                    intentCustomerId,
                    wl_id: workflowInstanceId,
                    workFlowDefinitionId: workflowDetail!.workflowDefinitionId,
                  })}`}
                >
                  编辑
                </ByButton>
              )}

              <ByButton
                type="error"
                size="large"
                variant="filled"
                className="flex-2 mr-2"
                onClick={onRejected}
              >
                驳回
              </ByButton>
              <ByButton size="large" className="flex-3" onClick={onApproved}>
                通过
              </ByButton>
            </ByRow>
          )
        }
      >
        <CustomerCard source={customerDetail?.intentCustomer} />

        <Card className="m-3">
          <ByCell label="类型" {...cellProps}>
            {getOption(data?.type, "label")}
          </ByCell>

          <ByCell label="备注" {...cellProps}>
            {data?.remark}
          </ByCell>

          <ByCell label="特殊说明" {...cellProps}>
            {data?.description}
          </ByCell>
        </Card>

        <ByCellGroup className="m-3">
          {data?.undertakers?.map((item, index) => (
            <Fragment key={index}>
              {index > 0 && (
                <View className="my-1 border-t-1 border-line-light" />
              )}

              <ByRow>
                <ByCol span={6}>
                  <ByCell label="承担人" vertical>
                    {item.userName}
                  </ByCell>
                </ByCol>
                <ByCol span={6}>
                  <ByCell label="承担金额" vertical>
                    <Money value={item.amount} />
                  </ByCell>
                </ByCol>
              </ByRow>
            </Fragment>
          ))}
        </ByCellGroup>

        {data?.details?.length > 0 && (
          <Card className="m-3">
            {data?.details.map((item, index) => (
              <>
                {index > 0 && (
                  <View className="my-2 border-t-1 border-line-light" />
                )}

                <DetailItem
                  source={item}
                  key={item?.quotaId || item.materialId}
                />
              </>
            ))}
          </Card>
        )}

        {workflowDetail && (
          <Card className="m-3">
            <ApprovalaProcess
              showTitle
              source={workflowDetail}
              onChangeStatus={setApproveNode}
            />
          </Card>
        )}
      </Page>

      <PageContainer round show={visible} onAfterLeave={() => onCancal()}>
        <PopupApproval />
      </PageContainer>
    </>
  );
};
